import WeaAssociativeSearch from '../base/wea-associative-search';
import addEventListener from 'rc-util/lib/Dom/addEventListener';
import T from 'prop-types';
import {Tabs, Row, Col} from 'antd';
// import  Tabs from '../../_antd1.11.2/Tabs';
import WeaTools from '../wea-tools';
const TabPane = Tabs.TabPane;
// import Row from '../../_antd1.11.2/Row';
// import Col from '../../_antd1.11.2/Col';
import classNames from 'classnames';
import isEmpty from 'lodash/isEmpty'
import isArray from 'lodash/isArray'
import Container from './container'
import './style/index.less'

class Main extends React.Component {
  static propTypes={
    value:T.string.isRequired,
    replaceDatas:T.array.isRequired,
  }
  constructor(props) {
    super(props);
    let defaultId = '',defaultName = '',activeKey='prov',
    selectedObj={
      counSelected:{id:'',name:''},
      provsSelected:{id:'',name:''},
      citySelected:{id:'',name:''},
      districtSelected:{id:'',name:''}
    };
    if(isArray(props.replaceDatas)&&props.replaceDatas.length>=3){
      const rD = props.replaceDatas;
      defaultId = rD[rD.length-1].id;
      defaultName = rD[rD.length-1].name;
      selectedObj['counSelected']= rD[0];
      selectedObj['provsSelected']= rD[1];
      selectedObj['citySelected']= rD[2];
      if(props.type=='263'){
        selectedObj['districtSelected']= rD[3];
        activeKey='district';
      }else{
        activeKey='city';
      }
    }
    this.state={
        id:defaultId,
        name:defaultName,
        url:props.dataUrl,
        isClearData: false,
        visible:false,
        countrys:[],
        provs:[],
        citys:[],
        districts:[],
        counSelected:selectedObj['counSelected'].id || '',
        provsSelected:selectedObj['provsSelected'].id || '',
        citySelected:selectedObj['citySelected'].id || '',
        districtSelected:props.type=='263'&&selectedObj['districtSelected'].id || '',
        activeKey:activeKey,
    }
    this.hideSearchAd = this.hideSearchAd.bind(this);
  }
  componentDidMount() {
      // this.componentDidUpdate();
  }
  componentWillReceiveProps(nextProps, nextState){
    // if(nextProps.value !== this.props.value && !nextProps.value){
    //   this.setState({value:''})
    // }
  }
  hideSearchAd(){
    this.setState({visible:false})
  }
  fetchTreeDatas=()=> {
    const {replaceDatas,type}=this.props;
    const isCountryBrowser = type=='258';
    const isProvBrowser = type=='2222';
    const {url,counSelected,provsSelected,citySelected,districtSelected,activeKey} = this.state;
    WeaTools.callApi(url,'GET').then(countrys => {

      // console.log('countrys',countrys.datas);
      this.setState({countrys:countrys.datas});
      countrys.datas.forEach((c)=>{
        if(!isCountryBrowser && c.id == counSelected){
          // console.log('counSelected',counSelected)
          WeaTools.callApi(`${url}${WeaTools.getFd(c)}&`,'GET').then(prov=>{

            // console.log('prov',prov.datas);
            this.setState({provs:prov.datas});
            prov.datas.forEach(p=>{
              if(!isProvBrowser && p.id==provsSelected){
                WeaTools.callApi(`${url}${WeaTools.getFd(p)}&`,'GET').then(city=>{

                  // console.log('city',city.datas);
                  this.setState({citys:city.datas});
                  this.props.type=='263' && city.datas.forEach(c=>{
                    if(c.id==citySelected){
                      WeaTools.callApi(`${url}${WeaTools.getFd(c)}&`,'GET').then(district=>{

                         // console.log('district',district.datas);
                         this.setState({districts:district.datas});
                      })
                    }
                  })
                })
              }
            })
          })
        }
      })
    })
  }
  alertModel = ()=>{
    const {replaceDatas,type}=this.props
      this.setState({visible:!this.state.visible})
      this.fetchTreeDatas();
      if(isArray(replaceDatas)&&replaceDatas.length==0||!replaceDatas){
        !this.state.id && this.countryClick(null,{type:"coun",id:1,isParent:true});//默认中国
        this.setState({
          visible:!this.state.visible,
          activeKey:this.state.activeKey || 'prov',
        })
      }

  }
  tabsChange=(activeKey)=>{
    this.setState({activeKey})
  }
  selectedSearch = (id,name)=>{
     this.props.onChange && this.props.onChange(id,name);
  }
  renderAsssosiate=()=>{
    const {type,value}=this.props;
    const {id,name,visible} = this.state;
    // console.log('renderAsssosiate------id',id,'name',name);
    return (
       <WeaAssociativeSearch
            {...this.props}
            isCity
            style={this.props.inputStyle}
            isClearData={this.state.isClearData}
            type={type}
            ids={id}
            names={name}
            modalVisable={visible}
            clickCallback={this.alertModel}
            onChange={this.selectedSearch}
            ref={r=>this.Ass=r}
        />
      );
  }
  countryClick=(e,obj)=>{
    const {type} = this.props;
    const isCountryBrowser = type=='258';
    !!e && e.stopPropagation();
    // console.log('countryClick=>obj',obj);
    let url = this.state.url;
    url = `${url}${WeaTools.getFd({...obj})}&`;
    if(isCountryBrowser){
      this.setState({
          counSelected:obj.id,
          id:obj.id,
          name:obj.name,
          visible:false,
      });
      return;
    }
    if(obj.isParent){
      WeaTools.callApi(url,'GET').then(datas => {
        // console.log('countryClick---datas',datas)
        this.setState({
          counSelected:obj.id,
          provs:datas.datas,
          activeKey:'prov',
        })
      });
    }else{
        this.setState({
          counSelected:obj.id,
          provs:[],
          activeKey:'prov',
        })
    }
  }
  provClick=(e,obj)=>{
    const {type} = this.props;
    const isProvBrowser = type=='2222';
    !!e && e.stopPropagation();
    // console.log('provClick==>',obj);
    let url = this.state.url;
    url = `${url}${WeaTools.getFd({...obj})}&`;
    if(isProvBrowser){
      this.setState({
          provsSelected:obj.id,
          id:obj.id,
          name:obj.name,
          visible:false,
      });
      return;
    }
    if(obj.isParent){
      WeaTools.callApi(url,'GET').then(datas => {
        this.setState({
          provsSelected:obj.id,
          citys:datas.datas,
          activeKey:'city',
        })
      });
    }
  }
  cityClick=(e,obj)=>{
    !!e && e.stopPropagation();
    // console.log('cityClick==>obj',obj);
    let url = this.state.url;
    url = `${url}${WeaTools.getFd({...obj})}&`;
    if(this.props.type=='58'){
      if(typeof this.props.onChange==='function'){
        this.props.onChange(obj.id,obj.name);
      }
      this.setState({
          citySelected:obj.id,
          id:obj.id,
          name:obj.name,
          visible:false,
      })
    }
    if(this.props.type == '263'){
      if(obj.isParent){
        WeaTools.callApi(url,'GET').then(datas => {
          this.setState({
            citySelected:obj.id,
            districts:datas.datas,
            activeKey:'district',
          })
        });
      }
    }
  }
  districtClick = (e,obj)=>{
    !!e && e.stopPropagation();
    // console.log('districtClick==>obj',obj);
    if(typeof this.props.onChange==='function'){
      this.props.onChange(obj.id,obj.name);
    }
    this.setState({
        districtSelected:obj.id,
        id:obj.id,
        name:obj.name,
        visible:false,
    })
  }
  renderTabs=()=>{
    const {countrys,provs,citys,districts,activeKey,counSelected,provsSelected,citySelected,districtSelected}=this.state;
    const {type} = this.props;
    // console.log('type---------',type,'countrys',countrys,'provs',provs)
    const style={
      cursor:'pointer'
    }
    const coountry = (
        <TabPane tab="国家" key="coun">
          <Row>
            {
             !isEmpty(countrys)&& countrys.map(item =>{
                const className = classNames({
                  spantag:true,
                  selected:counSelected==item.id || item.selected
                });
                return (
                    <Col span={4}>
                      <span className={className} {...item} style={style}  onClick={(e)=>{this.countryClick(e,item)}} >
                      {item.name}
                      </span>
                    </Col>
                );
              })
            }
          </Row>
        </TabPane>
      );
    const prov = (
      <TabPane tab="省份" key="prov">
          <Row>
            {
             !isEmpty(provs)&& provs.map(item =>{
                const className = classNames({
                  spantag:true,
                  selected:provsSelected==item.id || item.selected
                });
                return (
                  <Col span={4}>
                    <span className={className} {...item} style={style}  onClick={(e)=>{this.provClick(e,item)}} >
                      {item.name}
                    </span>
                  </Col>
                );
              })
            }
         </Row>
        </TabPane>
    );
    const city = (
      <TabPane tab="城市" key="city">
          <Row>
            {
             !isEmpty(citys)&& citys.map(item =>{
                const className = classNames({
                  spantag:true,
                  selected:citySelected==item.id || item.selected
                });
                return (
                  <Col span={4}>
                    <span className={className} {...item} style={style}  onClick={(e)=>{this.cityClick(e,item)}} >
                      {item.name}
                    </span>
                  </Col>
                );
              })
            }
          </Row>
        </TabPane>
    );
    const district = (
      <TabPane tab="区县" key="district">
         <Row>
              {
               !isEmpty(districts)&& districts.map(item =>{
                  const className = classNames({
                    spantag:true,
                    selected:districtSelected==item.id || item.selected
                  });
                  return (
                    <Col span={4}>
                      <span className={className} {...item} style={style}  onClick={(e)=>{this.districtClick(e,item)}} >
                        {item.name}
                      </span>
                    </Col>
                  );
                })
              }
            </Row>
        </TabPane>
    );
    let TabPaneArr = [];
    const coy = type == "258";
    const pv = type == "2222";
    const ciy = type == "58";
    const dist = type == "263";
    coy && TabPaneArr.push(coountry);
    pv && TabPaneArr.push([coountry,prov]);
    ciy && TabPaneArr.push([coountry,prov,city]);
    dist && TabPaneArr.push([coountry,prov,city,district]);

    // console.log('activeKey',activeKey);
    return (
      <Tabs type="card" activeKey={activeKey} onChange={this.tabsChange}>
       {TabPaneArr}
      </Tabs>
    );
  }
  render(){
    const {countrys,provs,citys,visible,}=this.state;
    const {type,layout,isAdSearch} = this.props;
    // console.log('this.Ass',this.Ass)
    // console.log('this.state.activeKey',this.state.activeKey);
    const assProps = this.Ass ? this.Ass.props : '';
    const refId = this.Ass ? this.Ass._reactInternalInstance._rootNodeID.replace(/[^a-zA-Z0-9]+/g,'') : '';
    const cn = `wea-city-picker-${refId}`;//唯一标识 for 定位
    return (
        <div className={`${cn}`}>
          {this.renderAsssosiate()}
          <Container layout={layout} getPopupContainer={()=> layout || document.body} visible={visible} parentClass={cn} refId={refId}>
            { this.renderTabs()}
          </Container>
          {isAdSearch && <div className="wea-city-picker-modal-mask" style={{display:visible ? 'block' : 'none'}} onClick={this.hideSearchAd}/>}
        </div>
    );
  }
}

export default Main;

